package com.atguigu.day01;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Ticket2 {
    public static void main(String[] args) {
        Resource2 resource2 = new Resource2();

        new Thread(() -> {
            for (int i = 0; i <50 ; i++) {
                try {
                    resource2.c1();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"窗口1").start();

        new Thread(() -> {
            for (int i = 0; i <50 ; i++) {
                try {
                    resource2.c2();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"窗口2").start();


        new Thread(() -> {
            for (int i = 0; i <50 ; i++) {
                try {
                    resource2.c3();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"窗口3").start();
    }
}





class Resource2{
    Lock lock = new ReentrantLock();
    Condition condition1 = lock.newCondition();
    Condition condition2 = lock.newCondition();
    Condition condition3 = lock.newCondition();

    private int ck=1;
    private int num=1;

    public void c1() throws InterruptedException {
        lock.lock();
        try{
            while (ck!=1){
                condition1.await();
            }
            if (num<=50){
                System.out.println(Thread.currentThread().getName()+"卖出了第"+(num++)+"张票");
                ck=2;
                condition2.signal();
            }
        }finally {
            lock.unlock();
        }
    }

    public void c2() throws InterruptedException {
        lock.lock();
        try{
            while (ck!=2){
                condition2.await();
            }
            if (num<=50){
                System.out.println(Thread.currentThread().getName()+"卖出了第"+(num++)+"张票");
                ck=3;
                condition3.signal();
            }
        }finally {
            lock.unlock();
        }
    }

    public void c3() throws InterruptedException {
        lock.lock();
        try{
            while (ck!=3){
                condition3.await();
            }
            if (num<=50){
                System.out.println(Thread.currentThread().getName()+"卖出了第"+(num++)+"张票");
                ck=1;
                condition1.signal();
            }
        }finally {
            lock.unlock();
        }
    }
}